package com.firewolf.shiro.realms;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

/**
 * 作者：刘兴
 * 时间:18/12/2
 **/
public class CustomRealm extends AuthorizingRealm {


    @Override
    public String getName() {
        return "这是我的自定义Realm"; //重写方法，更改自定义Realm的名字
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        String userName = (String) principals.getPrimaryPrincipal();
        //从数据库或者缓存中获取角色和权限数据
        Set<String> roles = new HashSet<>();
        roles.add("admin");
        roles.add("user");

        //权限数据
        Set<String> permissions = new HashSet<>();
        permissions.add("user:delete");
        permissions.add("user:add");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String userName = (String) token.getPrincipal();

        //根据用户名查询密码
        //构造AuthenticationInfo返回，这里就不去查询数据库了
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo("zhang", "123", getName());
        return authenticationInfo;
    }
}
